<template>
    <div v-if="hasSend" class="sent-success">
        <el-result icon="success" title="发送成功">

        </el-result>
    </div>
    <div class="write-wrapper" v-else-if="!hasSend && form">
        <el-form :model="form" ref="formRef" label-width="80px" :inline="false" :disabled="readOnly">
            <el-form-item label="收件人：">
                <el-select v-model="form.audienceId" multiple filterable remote reserve-keyword placeholder="请选择收件人"
                    :remote-method="remoteMethod" :loading="selectLoading">
                    <el-option v-for="item in accountOptions" :key="item.value" :label="item.label"
                        :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item label="主题：">
                <el-input v-model="form.subject" placeholder="请输入主题" clearable />
            </el-form-item>
        </el-form>

        <!-- 标题输入框（Element Plus） -->

        <div class="editor-box">
            <!-- 工具栏（WangEditor） -->
            <toolbar class="editor-tool " :editor="editorRef" />
            <!-- 编辑器（WangEditor） -->
            <Editor class="editor-body" v-model="form.body" :defaultConfig="editorConfig" :mode="mode"
                @onChange="onChange" @onCreated="onEditorCreated" />
        </div>
        <!-- 操作按钮（Element Plus） -->
        <div class="btn-group" v-if="!readOnly">
            <el-button type="primary" @click="handleSend" v-hasFunc="'msg:email:send'">发送</el-button>
            <el-button @click="handleDraft" v-hasFunc="'msg:email:save'">存草稿</el-button>
        </div>
    </div>

    <el-empty v-else description="暂无数据">

    </el-empty>

</template>

<script setup>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { saveEmails, sendEmails } from "@/api/msg/emails.js";
import { listEmailAccount } from "@/api/msg/emailaccount.js";
const { proxy } = getCurrentInstance()

// 标题
const formRef = ref();
const selectLoading = ref(false);
const accountOptions = ref([]);
const changeFlag = ref(false)
// 富文本内容
const editorRef = shallowRef();
const mode = "default"
const editorConfig = {
    placeholder: '请输入正文...',
    readOnly: false,
    // 你也可以在这里配置菜单栏、上传图片等更多内容
}
const hasSend = ref(false)
const isSaveForm = ref(false);
const readOnly = computed(() => {
    return form.value?.status !== 0;
})

const form = defineModel({
    type: Object
})




watch(() => form.value, (newValue, oldValue) => {
    if (isSaveForm.value) {
        changeFlag.value = false;
        isSaveForm.value = false;
        return;
    }
    if (newValue?.id != oldValue?.id) {
        hasSend.value = false;
        changeFlag.value = false;
        const p = { pageSize: 999, id: form.value.audienceId }
        resetAccountOptions(p)
        // 根据 readOnly 的值调用对应方法
        if (editorRef.value) {
            readOnly.value ? editorRef.value.disable() : editorRef.value.enable()
        }
    } else {
        changeFlag.value = true;
    }
}, { deep: true })




// 当编辑器创建完成时，会触发 onCreated 回调
const onEditorCreated = (editorInstance) => {
    editorRef.value = editorInstance
    // 可以在此执行一些初始化操作，如加载草稿内容等
}

//编辑器
const onChange = (editor) => {
    form.value.abstract = editor.getText().substring(0, 120);
}

// 存草稿
const handleDraft = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        return validateForm().then(() => {
            return saveEmails(form.value)
        }).then(res => {
            isSaveForm.value = true;
            proxy.$modal.msgSuccess("草稿保存成功");
            Object.assign(form.value, res);
        });
    }
}

//自动存草稿
const autoSaveDraft = () => {
    if (changeFlag.value) {
        return saveEmails(form.value).then((res) => {
            isSaveForm.value = true;
            Object.assign(form.value, res);
            proxy.$modal.msgSuccess("已自动存草稿");
        })
    }
}

//存草稿确认
const handleConfirmDraft = () => {
    if (readOnly.value) return Promise.resolve(false);
    if (changeFlag.value) {
        let confirmOption = {
            type: "warning",
            draggable: true,
            closeOnClickModal: false,
            distinguishCancelAndClose: true,
            cancelButtonText: "放弃",
            confirmButtonText: "存草稿"
        }
        return proxy.$confirm("是否存草稿", "提示", confirmOption).then(() => {
            return handleDraft();
        }).catch((action) => {
            let promise = action == "cancel" ? Promise.resolve(true) : Promise.reject(false);
            return promise;
        })
    }
    return Promise.resolve(true);
}

//发送
const handleSend = () => {
    const validateForm = formRef.value?.validate;
    if (validateForm) {
        validateForm().then(() => {
            sendEmails(form.value).then((res) => {
                proxy.$modal.msgSuccess("邮件发送成功");
                hasSend.value = true;
                form.value = {};
            });
        })
    }
}


const remoteMethod = (query) => {
    resetAccountOptions({ account: query })
}

//获取账号选项数据
const resetAccountOptions = (params) => {
    selectLoading.value = true;
    return listEmailAccount(params).then(({ result }) => {
        accountOptions.value = result.map(s => ({ label: s.account, value: s.id }))
    }).finally(() => {
        selectLoading.value = false;
    })
}

defineExpose({ saveConfirm: handleConfirmDraft, autoSaveDraft })

// 组件卸载时，需手动销毁 editor 实例，避免内存泄漏
onUnmounted(() => {
    if (editorRef.value) {
        editorRef.value.destroy()
        editorRef.value = null
    }
})
</script>

<style scoped lang="scss">
.sent-success {
    height: 100%;
    display: flex;
    justify-content: center;
}

.write-wrapper {
    padding: 10px;
    display: flex;
    flex-direction: column;
    height: 100%;
    overflow-y: auto;
    padding-bottom: 0;
}

.editor-box {
    border: 1px solid #ccc;
    margin-bottom: 20px;
    flex: 1;
    display: flex;
    flex-direction: column;

    .editor-tool {
        border: 1px solid #ccc;
        padding: 0 8px
    }

    .editor-body {
        flex: 1;
        overflow-y: auto;
    }
}

.title-input {
    margin-bottom: 16px;
}

.editor-container {
    margin-bottom: 16px;
}

.btn-group {
    // margin-bottom: 16px;
    text-align: right;
}

.preview-container {
    margin-top: 16px;
}
</style>